package com.gopay.gass.web.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.cps.dispatch.CPSCallRemoteService;

/**
 * Gass BaseController
 * 
 * @BaseController.java
 * @author GongZhong
 * @2012-12-25 下午3:18:36 www.gopay.com.cn Inc.All rights reserved.
 */
public class BaseController {

	protected Log logger = LogFactory.getLog(getClass());

	@SuppressWarnings("rawtypes")
	protected Map<String, String> getParamsFromRequest(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		for (Enumeration enumeration = request.getParameterNames(); enumeration
				.hasMoreElements();) {
			String eleName = (String) enumeration.nextElement();
			String eleValue = request.getParameter(eleName);
			params.put(eleName, eleValue);
            if ("verficationCode".equalsIgnoreCase(eleName)) {
                logger.error("网关收到的请求参数键: [" + eleName + "]，值: [" + StringUtils.abbreviateMiddle(eleValue, "*", 6) + "]");
            } else {
                logger.error("网关收到的请求参数键: [" + eleName + "]，值: [" + eleValue + "]");
            }
		}
		return params;
	}

	
	/**
     * 失败返回处理逻辑
     * @param request
     * @param response
     */
    protected void handleError(HttpServletResponse response, String errorCode) {
        try {
            StringBuffer xmlStr = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            xmlStr.append("<GopayTranRes>");
            xmlStr.append("<errCode>");
            xmlStr.append(errorCode);
            xmlStr.append("</errCode>");
            xmlStr.append("</GopayTranRes>");
            
            resp2Bis(response, "UTF-8", xmlStr.toString());
        }
        catch(GopayException ge) {
            logger.error("Gass 响应BIS请求出错：", ge);
        }
    }
    
    /**
     * 返回通知
     * 
     * @param response
     * @param enCode
     * @param resXml
     */
    protected void resp2Bis(HttpServletResponse response, String enCode, String resXml) throws GopayException {
        response.setContentType("text/xml;charset=" + enCode);
        try {
            response.getWriter().write(resXml);
            this.logger.info("Gass 成功响应BIS请求！");
        } catch (IOException e) {
            this.logger.error("Gass 响应BIS请求出错：", e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100F1002);
        }
        response.setStatus(HttpServletResponse.SC_OK);
    }
}